from kivyx.widgets import Rectangle

from amaze import directions


class PlayerW(Rectangle):
    def __init__(self, player):
        Rectangle.__init__(self)
        self.object = player
        self.size = 1, 1
        self.center = player.coords
        self.rgba = (0, 0, 1, 1)

    def update(self):
        self.center = self.object.coords

    def on_touch_down(self, touch):
        if self.collide_point(touch.x, touch.y):
            touch.grab(self)
            touch.ud.path = [self.object.tile]
            return True
        else:
            return False

    def on_touch_move(self, touch):
        if touch.grab_current is self:
            tile = touch.ud.path[-1]
            x = int(touch.x)
            y = int(touch.y)
            if x == tile.x and y == tile.y:
                return True

            direction = directions.from_delta(x - tile.x, y - tile.y)
            self.object.path.append(direction)

            try:
                new_tile = self.object.maze[x, y]
            except IndexError:
                # invalidate_touch(touch)
                pass
            touch.ud.path.append(new_tile)

            return True
        return False

    def on_touch_up(self, touch):
        if touch.grab_current is self:
            touch.ungrab(self)
            return True
        return False


class PathManager(object):
    def __init__(self):
        pass

    def check_touch(self, touch):
        x = int(touch.x)
        y = int(touch.y)
        try:
            tile = self.widget.object.maze[x, y]
        except IndexError:
            return False
        try:
            index = self.tiles.index(tile)
        except ValueError:
            return False

        del self.tiles[index+1:]

        self.tiles.append(self.widget.object.tile)
        self.touch = touch
        self.widget.grab(touch)



